<?php
/**
 * Created by PhpStorm.
 * User: zhiduopin-PC
 * Date: 2018/11/1
 * Time: 15:37
 */
namespace app\admin\model;

use think\Db;
use think\wyyxapi\WyYxAPI;
class RoomMembers extends DataBase{
    protected $autoWriteTimestamp = true;



    /**
     * @title 踢出房间
     * @user 帅帅吴
     * @date 2019/02/21
     * @time 11:00
     */
    public function kickUser()
    {
        $user_id = input('user_id');  //被踢的人
        $room_id = input('room_id');  //房间
        return $this->dealKick($user_id,$room_id);
    }

    //批量踢出房间
    public function kickAllUser()
    {
        $userIds = input('get.user_id');
        $room_id = input('get.room_id');
        //  halt($room_id);
        $userIds = explode(',',$userIds);
        foreach($userIds as $v){
            $res = $this->dealKick($v,$room_id);
        }
        return $res;


        //dump($userIds);
    }

    //处理踢人
    public function dealKick($user_id,$room_id)
    {
        $wyWxModel = new WyYxAPI();

        Db::Connect('db_data')->startTrans();
        try{
            $memberInfo = $this->where([['user_id','=',$user_id],['room_id','eq',$room_id]])->find();
            if(empty($memberInfo)) return ['code'=>-100,'msg'=>'用户不在房间里'];

            $userInfo = User::where('id','=',$user_id)->field('u_id,pic,nickname,signature,kick_room')->find();
            $userInfo['nickname'] = preg_replace_callback('/@E(.{6}==)/', function ($r) {
                return base64_decode($r[1]);
            }, $userInfo['nickname']);

            if(empty($userInfo['pic'] ))
                $userInfo['pic'] = config('site_url').'/static/admin/images/nickPic.png';

            $leave_user = ['nickName'=>$userInfo['nickname'],'type'=>3,'action'=>-1,'account'=>(string)$user_id,'pic' => $userInfo['pic'],'signature' => $userInfo['signature']];
            $leave_user = json_encode($leave_user);


            $roomInfo = Room::where('id','=',$room_id)->find();

            //如果在房间里
            if(!empty($memberInfo)){

                //保存最近的被踢出的房间集合
                $kick_room =unserialize($userInfo['kick_room']);
                $kick_room[$room_id] = time();
                $kick_room = serialize($kick_room);
                User::where('id','=',$user_id)->update(['kick_room'=>$kick_room]);

                $chat_id  =(string)$roomInfo['chat_id'];  //网易id
                $user_seat  = $memberInfo['seat'];    //用户在房间的位置

                $seat_lock = explode(',',$roomInfo['seat_lock']);  //房间的位置锁
                $seat_voice = explode(',',$roomInfo['seat_voice']);  //房间的声音锁

                $arr['seat']  = $user_seat;
                //如果用户的位置已经被锁
                if(in_array($user_seat,$seat_lock)) $arr['is_lock'] = 0;
                else $arr['is_lock'] = 1;
                //如果用户的位置声音被锁
                if(in_array($user_seat,$seat_voice)) $arr['is_voice'] = 0;
                else $arr['is_voice'] = 1;

                //房间里被封禁的座位和用户上麦的座位总和
                $seat_num = RoomMembers::where([['room_id','=',$room_id],['seat','<>',0]])->count();  //在麦
                $seat_num += count($seat_lock);  //在麦加上被封禁的座位

                //如果该用户在麦
                if($user_seat != 0){

                    //查看第一个排队上麦的用户
                    $sort = SortWheat::where('room_id','=',$room_id)->order('create_time ASC')->limit(1)->select()->toArray();

                    if($user_seat && !in_array($user_seat,$seat_lock) && ($seat_num == 8)) {

                        //第一个排队的用户信息
                        $queue_user = User::where('id', '=', $sort[0]['user_id'])->field('nickname,id,u_id,pic,signature')->find();

                        //查看排队的用户是否在房间
                        $queue_mem = RoomMembers::where([['user_id', $sort[0]['user_id']], ['room_id', $room_id]])->find();

                        //确定发送房间消息内容
                        $queue_user = ['status'=>$queue_mem['status'],'seat'=>$user_seat,'is_lock'=>1];
                        if (in_array($user_seat, $seat_voice)) $queue_user['is_voice'] = 0;
                        else $queue_user['is_voice'] = 1;
                        $arr = ['seat' => [$queue_user], 'type' => 6, 'action' => 1, 'account' => $user_id];
                        $attach = json_encode($arr);

                        //如果排麦用户还在该房间
                        if(!empty($queue_mem)) {
                            //如果在房间，则顶替被踢出的位置
                            RoomMembers::where([['user_id', $sort[0]['user_id']], ['room_id', $room_id]])->update(['seat' => $user_seat]);
                            //将用户踢出房间
                            RoomMembers::where('user_id', '=', $user_id)->delete();
                            //删除排麦的数据
                            SortWheat::where([['user_id', $sort[0]['user_id']], ['room_id', $room_id]])->delete();
                            //发送房间信息，用户被踢出
                            $msg_leave = sendAttachMsg($chat_id, $user_id, $leave_user);
                            //发送房间信息，排麦用户已被取消排麦
                            $msg_enter = sendAttachMsg($chat_id, $roomInfo['r_id'], $attach);
                        }
                        //如果排麦用户不在该房间
                        if (empty($queue_mem)) {
                            //将用户踢出房间
                            RoomMembers::where('user_id', '=', $user_id)->delete();
                            //删除排麦的数据
                            SortWheat::where([['user_id', $sort[0]['user_id']], ['room_id', $room_id]])->delete();
                            //发送房间信息，用户被踢出
                            $msg_leave = sendAttachMsg($chat_id, $user_id, $leave_user);
                            //发送房间信息，排麦用户已被取消排麦
                            $msg_enter = sendAttachMsg($chat_id, $roomInfo['r_id'], $attach);
                            if($msg_leave['code'] != 200  ||  $msg_enter['code'] != 200){
                                Db::Connect('db_data')->rollback();
                                return ['code'=>-100,'msg'=>'踢出失败:踢出消息：'.$msg_leave['desc'].'进入消息：'.$msg_enter['desc']];
                            }
                        }

                    }else{
                        //将用户踢出房间
                        RoomMembers::where('user_id', '=', $user_id)->delete();
                        //发送房间信息，用户被踢出
                        $msg_leave = sendAttachMsg($room_id, $user_id, $leave_user);
                        if($msg_leave['code'] != 200){
                            Db::Connect('db_data')->rollback();
                            return ['code'=>-100,'msg'=>'踢出失败:'.$msg_leave['desc']];
                        }
                    }
                }
                //用户在房间，但没上麦
                if($user_seat == 0){
                    //  将用户踢出房间
                    RoomMembers::where('user_id', '=', $user_id)->delete();

                    $array = ['seat'=>[],'type'=>6,'action'=>1,'account'=>$user_id];
                    $attach = json_encode($array);
                    // 发送房间信息，用户被踢出
                    $msg_leave =sendAttachMsg((string)$roomInfo['chat_id'], (string)$roomInfo['r_id'], json_encode($leave_user));
                    //   halt($msg_leave);
                    if($msg_leave['code'] == 200)
                        $msg = sendAttachMsg((string)$roomInfo['chat_id'],(string)$roomInfo['r_id'],$attach);
                    if($msg_leave['code'] != 200){
                        Db::Connect('db_data')->rollback();
                        return ['code'=>-100,'msg'=>'踢出失败:'.$msg_leave['desc']];
                    }
                }
                Db::Connect('db_data')->commit();
                return ['code'=>100,'msg'=>'踢出成功'];
            }

        }catch(\Exception $e){
            Db::Connect('db_data')->rollback();
            return ['code'=>-100,'msg'=>'踢出失败:'.$e->getMessage()];

        }
    }

}